package com.coisshi.base.module.mqtt.service;

import cn.hutool.core.util.StrUtil;
import com.coisshi.base.common.exception.BizException;
import com.coisshi.base.framework.config.properties.MqttProperties;
import com.coisshi.base.module.mqtt.dto.MqttPublishDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * MQTT 发布服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MqttPublisherService {

    private final MqttClient mqttClient;
    private final MqttProperties mqttProperties;

    /**
     * 发布MQTT消息
     * @param dto 消息入参
     */
    public void publish(MqttPublishDto dto) throws BizException {
        try {
            MqttMessage message = new MqttMessage(dto.getMessage().getBytes(StandardCharsets.UTF_8));
            message.setQos(dto.getQos() != null ? dto.getQos() : mqttProperties.getQos());

            mqttClient.publish(StrUtil.blankToDefault(dto.getTopic(), mqttProperties.getDefaultTopic()), message);
            log.info("MQTT消息已发送: topic={}, message={}", dto.getTopic(), dto.getMessage());
        } catch (MqttException e) {
            throw new BizException("MQTT消息发送失败" + e.getMessage());
        }
    }
} 